package com.ruoyi.starbucks.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.HttpResponseResult;
import com.ruoyi.common.utils.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.starbucks.domain.*;
import com.ruoyi.starbucks.mapper.*;
import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.Unirest;
import org.apache.commons.compress.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.starbucks.service.IStarbucksAccountService;
import org.springframework.transaction.annotation.Transactional;

import static com.ruoyi.common.utils.http.HttpsUtils.*;

/**
 * 星巴克账号Service业务层处理
 *
 * @author ruoyi
 * @date 2021-01-03
 */
@Service("starbucksAccountService")
public class StarbucksAccountServiceImpl implements IStarbucksAccountService {
    private static final Logger log = LoggerFactory.getLogger(StarbucksAccountServiceImpl.class);

    @Autowired
    private StarbucksAccountMapper starbucksAccountMapper;

    @Autowired
    private StarbucksAccountExtMapper starbucksAccountExtMapper;

    @Autowired
    private StarbucksCardsMapper starbucksCardsMapper;

    @Autowired
    private StarbucksCardsExtMapper starbucksCardsExtMapper;

    @Autowired
    private StarbucksRewardsMapper starbucksRewardsMapper;

    @Autowired
    private StarbucksRewardsExtMapper starbucksRewardsExtMapper;

    /** 获取代理地址 */
    @Value("${getProxyIpUrl}")
    private String getProxyIpUrl;

    /**
     * 查询星巴克账号
     *
     * @param id 星巴克账号ID
     * @return 星巴克账号
     */
    @Override
    public StarbucksAccount selectStarbucksAccountById(BigInteger id) {
        return starbucksAccountMapper.selectStarbucksAccountById(id);
    }

    /**
     * 查询星巴克账号列表
     *
     * @param starbucksAccount 星巴克账号
     * @return 星巴克账号
     */
    @Override
    public List<StarbucksAccount> selectStarbucksAccountList(QueryStarbucksAccount starbucksAccount) {
        return starbucksAccountExtMapper.selectStarbucksAccountList(starbucksAccount);
    }

    /**
     * 新增星巴克账号
     */
    @Override
    public AjaxResult insertStarbucksAccount(String token, String isNewAccount, String deviceName,String phoneNo) {
        StarbucksAccount starbucksAccount = new StarbucksAccount();
        starbucksAccount.setToken(token);
        starbucksAccount.setIsNewAccount(isNewAccount);
        starbucksAccount.setDeviceName(deviceName);
        starbucksAccount.setCellPhone(phoneNo);
        starbucksAccount.setCreateTime(DateUtils.getNowDate());
        int count = starbucksAccountMapper.insertStarbucksAccount(starbucksAccount);
        log.info("新增星巴克账号共{}条",count);
        return count > 0 ? AjaxResult.success(starbucksAccount) : AjaxResult.error("新增失败");
    }

    /**
     * 同步账号信息
     */
    @Override
    public AjaxResult getAccountDetail(String token) {
        StarbucksAccount starbucksAccount = starbucksAccountExtMapper.selectInfoByToken(token);
        if (starbucksAccount == null) {
            log.info("没有此token");
            return AjaxResult.error(MessageUtils.message("not.token"));
        }
        String url = "https://profile.starbucks.com.cn/api/account/detail";
        Map<String, Object> map = new HashMap<>();
        map.put("Content-Type", "application/x-www-form-urlencoded");
        map.put("Authorization", "Bearer " + token);
        HttpResponseResult result = null;
        try {
            Date nowDate = DateUtils.getNowDate();
            updateIp();
            result = sendGet(url, null, map,proxyHost,proxyPort);
            if (!checkStarbucks(result)){
                return getAccountDetail(token);
            }
            //无法获取用户信息
            if (result.getResponse().getStatusLine().getStatusCode()==401){
                starbucksAccount.setIsValid("0");
                starbucksAccount.setFailureTime(nowDate);
                int count = starbucksAccountMapper.updateStarbucksAccount(starbucksAccount);
                log.error("无法获取用户信息共{}条,id:{}",count,starbucksAccount.getId());
                return AjaxResult.error(401,"无法获取用户信息");
            }
            //将获取到的信息更新到数据库
            JSONObject jsonObject = JSONObject.parseObject(result.getResponseEntity());
            starbucksAccount.setCellPhone(jsonObject.getString("mobile"));
            starbucksAccount.setUserId(jsonObject.getString("userId"));
            starbucksAccount.setUserName(jsonObject.getString("username"));
            //获取到的时间搓,转换为时间
            String createTime = jsonObject.getString("createTime");
            starbucksAccount.setSince(DateUtils.stampToDate(createTime));
            starbucksAccount.setIsValid("1");
            starbucksAccount.setUpdateTime(nowDate);
            starbucksAccount.setSyncTime(nowDate);
            int count = starbucksAccountMapper.updateStarbucksAccount(starbucksAccount);
            log.info("更新用户信息共{}条", count);
            return AjaxResult.success(jsonObject);
        } catch (Exception e) {
            log.error("出错信息:",e);
            log.error("getAccountDetail更新信息失败,id:{}，失败请求结果：{}", starbucksAccount.getId(), result.getResponse());
            return AjaxResult.error("用户账号更新失败，用户主键id："+starbucksAccount.getId(),result.getResponse());
        }
    }

    /**
     * 同步用户信息(查星星接口)
     */
    @Override
    public AjaxResult getStar(String token) {
        StarbucksAccount starbucksAccount = starbucksAccountExtMapper.selectInfoByToken(token);
        if (starbucksAccount == null) {
            log.info("没有此token");
            return AjaxResult.error(MessageUtils.message("not.token"));
        }
        if (starbucksAccount.getIsValid()!=null&&starbucksAccount.getIsValid().equals("0")){
            return AjaxResult.error("无法获取用户信息");
        }
        String url = "https://profile.starbucks.com.cn/api/Customers/detail";
        Map<String, Object> map = new HashMap<>();
        map.put("Content-Type", "application/x-www-form-urlencoded");
        map.put("Authorization", "Bearer " + token);
        HttpResponseResult result = null;
        try {
            updateIp();
            result = sendGet(url, null, map,proxyHost,proxyPort);
            if (!checkStarbucks(result)){
                return getStar(token);
            }
            //将获取到的信息更新到数据库
            JSONObject jsonObject = JSONObject.parseObject(result.getResponseEntity());
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
            starbucksAccount.setBirthday(sdf.parse(jsonObject.getString("birthday")));
            starbucksAccount.setLastName(jsonObject.getString("lastName"));
            starbucksAccount.setGender(jsonObject.getString("gender"));
            starbucksAccount.setFirstName(jsonObject.getString("firstName"));
            starbucksAccount.setUserName(jsonObject.getString("userName"));
            starbucksAccount.setCellPhone(jsonObject.getString("cellPhone"));
            starbucksAccount.setLoyaltyPoints(jsonObject.getFloat("loyaltyPoints"));
            starbucksAccount.setLoyaltyTier(jsonObject.getString("loyaltyTier"));
            starbucksAccount.setPointsToNextTier(jsonObject.getFloat("pointsToNextTier"));
            starbucksAccount.setNextTierName(jsonObject.getString("nextTierName"));
            Date nowDate = DateUtils.getNowDate();
            starbucksAccount.setUpdateTime(nowDate);
            starbucksAccount.setSyncTime(nowDate);
            int count = starbucksAccountMapper.updateStarbucksAccount(starbucksAccount);
            log.info("更新基本信息共{}条", count);
            return AjaxResult.success(jsonObject);
        } catch (Exception e) {
            log.error("出错信息:",e);
            log.error("getStar更新信息失败,id:{}，失败请求结果：{}",starbucksAccount.getId(), result.getResponse());
            return AjaxResult.error("用户信息更新失败，用户主键id："+starbucksAccount.getId(),result.getResponse());
        }
    }

    /**
     * 同步卡片信息
     */
    @Transactional
    @Override
    public AjaxResult getCards(String token) {
        StarbucksAccount starbucksAccount = starbucksAccountExtMapper.selectInfoByToken(token);
        if (starbucksAccount == null) {
            log.info("没有此token");
            return AjaxResult.error(MessageUtils.message("not.token"));
        }
        if (starbucksAccount.getIsValid()!=null&&starbucksAccount.getIsValid().equals("0")){
            return AjaxResult.error("无法获取用户信息");
        }
        try {
            HttpResponse<JsonNode> response = Unirest.post("https://cards.starbucks.com.cn/cards//")
                    .header("Host-Type", "cards.starbucks.com.cn")
                    .header("Connection", "keep-alive")
                    .header("Access-Control-Request-Method", "POST")
                    .header("Origin", "https://www.starbucks.com.cn")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML like Gecko) Chrome/78.0.3904.108 Safari/537.36")
                    .header("Access-Control-Request-Headers", "access-control-allow-origincontent-typex-api-version")
                    .header("Accept", "*/*")
                    .header("Sec-Fetch-Site", "same-site")
                    .header("Sec-Fetch-Mode", "cors")
                    .header("Referer", "https://www.starbucks.com.cn/account/")
                    .header("Accept-Encoding", "gzip deflate br")
                    .header("Accept-Language", "zh-CNzh;q=0.9")
                    .header("Authorization", "Bearer " + token)
                    .header("accept", "application/json")
                    .asJson();
            if (response.getStatus() != HttpStatus.SUCCESS){
                log.error("getCards更新信息失败,id:{}，失败请求返回结果：{}",starbucksAccount.getId(), response);
                return AjaxResult.success("更新卡片信息失败");
            }
            JSONObject jsonObject = null;
            JSONArray jsonArray = null;
            try {
                jsonObject = JSONObject.parseObject(String.valueOf(response.getBody()));
                jsonArray = jsonObject.getJSONArray("data");
            }catch (Exception e){
                e.printStackTrace();
                log.error("getCards更新信息失败,id:{}，失败请求返回结果：{}",starbucksAccount.getId(), response.getBody());
                return AjaxResult.success("更新卡片信息失败");
            }
            int count = 0;
            //将用户的卡片同步到历史表
            String userId = starbucksAccount.getUserId();
            int insertCount = starbucksCardsExtMapper.insertCardsToCardsHistory(userId);
//            log.info("同步历史卡片信息共{}条",insertCount);
            //删除卡片信息
            int delCount = starbucksCardsExtMapper.delCardsByUserId(userId);
//            log.info("删除用户id:{}的卡片信息共{}条",userId,delCount);
            //将获取到的信息更新到数据库
            for (Object object : jsonArray) {
                JSONObject jo = (JSONObject) object;
                JSONObject qrseed = jo.getJSONObject("qrseed");
                StarbucksCards starbucksCards = new StarbucksCards();
                starbucksCards.setUserId(starbucksAccount.getUserId());
                starbucksCards.setToken(starbucksAccount.getToken());
                starbucksCards.setReason(jo.getString("reason"));
                starbucksCards.setPurchaseDate(DateUtils.parseDate(jo.getString("purchaseDate")));
                //是否物理卡
                String isPhysical = "true".equals(jo.getString("isPhysical"))?"1":"0";
                starbucksCards.setIsPhysical(isPhysical);
                starbucksCards.setCardType(jo.getString("cardType"));
                starbucksCards.setActiveCardChannel(jo.getString("activeCardChannel"));
                starbucksCards.setPurchaseStore(jo.getString("purchaseStore"));
                starbucksCards.setExpiryDate(DateUtils.parseDate(jo.getString("expiryDate")));
                starbucksCards.setDomain(jo.getString("domain"));
                starbucksCards.setCardNumber(jo.getString("cardNumber"));
                starbucksCards.setCardStatus(jo.getString("cardStatus"));
                starbucksCards.setMemberId(jo.getString("memberId"));

                starbucksCards.setQrseedExpiredAt(DateUtils.dealDateFormat(qrseed.getString("expiredAt")));
                starbucksCards.setQrseedOpenId(qrseed.getString("openId"));
                starbucksCards.setQrseedToken(qrseed.getString("token"));
                try {
                    starbucksCards.setBalance(qrseed.getBigDecimal("balance"));
                }catch (Exception ignored){}
                starbucksCards.setCreateTime(DateUtils.getNowDate());
                count += starbucksCardsMapper.insertStarbucksCards(starbucksCards);
            }
            log.info("更新卡片信息共{}条", count);
            return AjaxResult.success(jsonObject);
        } catch (Exception e) {
            log.error("getCards更新信息失败,id:{}，出错信息：{}",starbucksAccount.getId(), e);
            return AjaxResult.error("卡片更新失败，用户主键id："+starbucksAccount.getId());
        }
    }

    /**
     * 同步优惠券信息
     */
    @Transactional
    @Override
    public AjaxResult getRewards(String token) {
        StarbucksAccount starbucksAccount = starbucksAccountExtMapper.selectInfoByToken(token);
        if (starbucksAccount == null) {
            log.info("没有此token");
            return AjaxResult.error(MessageUtils.message("not.token"));
        }
        if (starbucksAccount.getIsValid()!=null&&starbucksAccount.getIsValid().equals("0")){
            return AjaxResult.error("无法获取用户信息");
        }
        updateIp();
        Map<String, Object> header = new HashMap<>();
        header.put("Accept", "application/json");
        header.put("X-API-Version", "2.0");
        header.put("Content-Type", "application/json");
        header.put("Host", "bff.starbucks.com.cn");
        header.put("Connection", "Keep-Alive");
        header.put("Accept-Encoding", "gzip");
        header.put("User-Agent", "com.starbucks.cn/7.28.0");
        header.put("x-phone-type", "ANDROID");
        header.put("x-app-version", "7.28.0");
        header.put("Authorization", "Bearer " + token);
        final String randomIp = IpUtils.getRandomIp();
        header.put("X-Forwarded-For", randomIp);
        header.put("X-Real-IP", randomIp);
        header.put("CLIENT_IP", randomIp);
        header.put("VIA", randomIp);
        header.put("REMOTE_ADDR", randomIp);
        String response = sendGet("https://bff.starbucks.com.cn/common-api/v1/coupons?channel=ALL&lang=zh_CN&page_num=1&appid=859977c6f22b4f9ce98d4b02d031b4a8&timestamp=1614852155030&sign=ELIeyTSlQAUoNI1vIoTTGd8CHzbWuOil%2BfJ9gFcijAR4BC%2F8X5VuXcGHHkvY2krc3WG3ynUWziFM%0AR0YGZbgzwHGRyCge2NMpNYa4KDANO9aCc7RVlFKbkFoBFWsCs8dopY2%2Fo1XTwLLPkwG4Ou%2Bu4KVW%0Acf0AwOLzHq3Y%2F8zU%2F4I%3D%0A", null
                , header,proxyHost,proxyPort).getResponseEntity();
        if(response!=null){
        JSONArray body = JSONObject.parseObject(response).getJSONObject("data").getJSONArray("coupons");
            try {
                int count=0;
                if (body.size() != 0) {
                    for (int i = 0; i < body.size(); ++i) {
                        JSONObject reward = body.getJSONObject(i);
                        StarbucksRewards starbucksRewards = new StarbucksRewards();
                        starbucksRewards.setUserId(starbucksAccount.getUserId());
                        starbucksRewards.setToken(starbucksAccount.getToken());
                        starbucksRewards.setCreateTime(DateUtils.getNowDate());
                        starbucksRewards.setStatus(reward.getString("status"));
                        starbucksRewards.setMemberBenefitId(reward.getString("memberBenefitId"));
                        starbucksRewards.setUsageDescription(reward.getString("usageDescription"));
                        starbucksRewards.setBenefitId(reward.getString("benefitId"));
                        starbucksRewards.setAlternativeDescription(reward.getString("title"));
                        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
                        starbucksRewards.setExpiryDate(sdf.parse(reward.getString("expiredDate")));
                        count += starbucksRewardsMapper.insertStarbucksRewards(starbucksRewards);
                    }
                    log.info("更新优惠券信息共{}条", count);
                }
            }
            catch (Exception e){
                log.error("出错信息:",e);
            }
            return AjaxResult.success(body);
        }
        return AjaxResult.success(null);
    }

    /**
     * 插入token(每个token一行)
     */
    @Transactional
    @Override
    public AjaxResult insertByToken(String token) {
        String tokens[] = token.split("\\n");
        log.info("开始新增token：");
        Date nowDate = DateUtils.getNowDate();
        int count=0;
        for (String tokenStr : tokens) {
            StarbucksAccount starbucksAccount = new StarbucksAccount();
            starbucksAccount.setToken(tokenStr.trim());
            starbucksAccount.setCreateTime(nowDate);
            int i = starbucksAccountMapper.insertStarbucksAccount(starbucksAccount);
            if (i <= 0) {
                log.info("token：{}，新增失败", tokenStr);
            }
            count++;
        }
        log.info("共新增"+count+"条token");
        return AjaxResult.success("共新增"+count+"条token");
    }

    /**
     * 批量新增。本地文件（入口）
     */
    @Override
    public AjaxResult insertStarbucksAccountAll() {
        String fileName = "F:/ck.txt";
        File file = new File(fileName);
        BufferedReader reader = null;
        String tempString = null;
        int count=0;
        try {
            log.info("开始新增token：");
            reader = new BufferedReader(new FileReader(file));
            Date nowDate = DateUtils.getNowDate();
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                if (tempString.isEmpty()) {
                    continue;
                }
                StarbucksAccount starbucksAccount = starbucksAccountExtMapper.selectInfoByToken(tempString);
                if(starbucksAccount!=null){
                    //该token已存在
                    log.info("token:{},已存在",tempString);
                    continue;
                }
                starbucksAccount = new StarbucksAccount();
                starbucksAccount.setToken(tempString);
                starbucksAccount.setCreateTime(nowDate);
                int i = starbucksAccountMapper.insertStarbucksAccount(starbucksAccount);
                // 显示行号
                if (i <= 0) {
                    log.info("token：{}，新增失败", tempString);
                }
                count++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ignored) {
                }
            }
        }
        log.info("共新增"+count+"条token");
        return AjaxResult.success("共新增"+count+"条token");
    }

    /**
     * 更新此id的全部信息
     */
    @Override
    public AjaxResult updateInfoById(BigInteger id) {
        log.info("开始同步id:{}的信息",id);
        StarbucksAccount starbucksAccount = starbucksAccountMapper.selectStarbucksAccountById(id);
        getAccountDetail(starbucksAccount.getToken());
        getStar(starbucksAccount.getToken());
        //getCards(starbucksAccount.getToken());
        getRewards(starbucksAccount.getToken());
        log.info("同步完成");
        return AjaxResult.success();
    }

    /**
     * 批量更新信息
     */
    @Override
    public AjaxResult updateInfo(Date startTime , Date endTime) {
        List<StarbucksAccount> starbucksAccountList = starbucksAccountExtMapper.selectStarbucksAccountListByTime(startTime,endTime,0);
        log.info("时间段{}至{}之间，查询出需要更新的信息{}条",startTime,endTime,starbucksAccountList.size());
        Thread t = new Thread(new Runnable(){
            public void run(){
                int count = 0;
                for (StarbucksAccount starbucksAccount : starbucksAccountList) {
                    log.info("当前操作id：{}",starbucksAccount.getId());
//                    if (starbucksAccount.getId().compareTo(new BigInteger("3402"))<1){continue;}
                    AjaxResult result = getAccountDetail(starbucksAccount.getToken());
                    //没有用户信息的不跑
                    if (result.get("code").toString().equals("401")){ continue; }
                    getStar(starbucksAccount.getToken());
                   // getCards(starbucksAccount.getToken());
                    getRewards(starbucksAccount.getToken());
                    count++;
                }
                log.info("更新数据共" + count + "条");
            }});
        t.start();
        log.info("正在更新数据,共" + starbucksAccountList.size() + "条");
        return AjaxResult.success("正在更新数据,共" + starbucksAccountList.size() + "条");
    }

    /**
     * 一键答题
     */
    @Override
    public AjaxResult answer(String token) {
        StarbucksAccount starbucksAccount = starbucksAccountExtMapper.selectInfoByToken(token);
        if (starbucksAccount == null) {
            log.info("没有此token");
            return AjaxResult.error(MessageUtils.message("not.token"));
        }
        String url = "https://bff.starbucks.com.cn/inbox/api/inbox?limit=10&offset=0&lang=zh&nonce=UD0eT%7EAz6CpU-XNa&sign=EQPCvub0%2Fq3WdtTqe%2BFZecdZioMIqWP%2FU%2FlYbikBY6XGQsclHs9WtI7za4V%2B3LGxlWCT9TAZsRwmRysLx909DFqE6jtafKm2irURYf%2FWrLLBSX3O0V%2F1aIKW442%2BcvbLturhSEAtr942z8ut%2BOViygdt%2BFqQRiaLMrl0mXRTS25VC%2F6OB9%2Fxy8Cwpf81uYgwwbV%2BYJuJ9UvHPIubU3FQC0UwxBlNw41XNXMlsyNEYVSB522eICrknuC81ilD2Rj%2F5jgt%2FMofjkAS5CneXCB8SyRd%2FuQEcTn5fDR7C5ynmp8uiv3HzNbxRhCP%2FkMd2bTQpUFk5eXDDALD9u4fXBIIbA%3D%3D";
        Map<String, Object> map = new HashMap<>();
        map.put("Connection", "keep-alive");
        map.put("Accept", "*/*");
        map.put("User-Agent", "Starbucks/7.19.0 (com.starbuckschina.mystarbucksmoments; build:3711; iOS 12.2.0) Alamofire/5.1.0");
        map.put("Accept-Language", "zh-Hans-CN;q=1.0");
        map.put("Accept-Encoding", "br;q=1.0, gzip;q=0.9, deflate;q=0.8");
        map.put("Authorization", "Bearer " + token);
        HttpResponseResult result = null;
        JSONArray jsonArray =null;
        try {
            result = sendGet(url, null, map);
            if (!checkStarbucks(result)) {
                return getAccountDetail(token);
            }
            String responseEntity = result.getResponseEntity();
            String title = "诚邀您参与啡快™顾客体验调查";
            if (responseEntity.contains(title)){
                JSONObject jo = (JSONObject) JSONObject.parse(result.getResponseEntity());
                jsonArray = jo.getJSONArray("data");
                for (Object object: jsonArray) {
                    String str = object.toString();
                    if (!str.contains(title)){continue;}
                    AnswerData answerData = SerializeUtils.deserialize(str,AnswerData.class);
                    if (answerData == null){
                        log.info("转换实体类失败,转换对象为:"+object);
                        continue;
                    }
                    String urlQuery = StringUtils.substring(answerData.getCtaUrl(), answerData.getCtaUrl().indexOf("=") + 1);
                    String answerUrl = "https://mopsurvey.starbucks.com.cn/q/question/OxrbxP?uid=" + URLEncoder.encode(urlQuery);
                    //进行答题
                    AnswerQuestionData questionData = submitAnswer(answerUrl,token,"",0);
                    log.info("答题返回："+questionData);
                    if (questionData.getMessage()!=null && !questionData.getMessage().equals("您已经参与过本次调查")){
                        while(true){
                            for (int i =0;i<=3;i++){
                                questionData = submitAnswer(questionData.getUrl(),questionData.getToken(),questionData.getParams(),questionData.getId());
                                if (!questionData.getMessage().equals("")){
                                    break;
                                }
                            }
                            if (questionData.getMessage().equals("")||questionData.getMessage().equals("成功")){
                                continue;
                            }
                            if (questionData.getMessage().equals("感谢您的参与")){
                                return AjaxResult.success("答题成功");
                            }
                        }
                    }else{
                        return AjaxResult.success("您已经参与过本次调查");
                    }
                }
            }else{
                log.info("token为{},id为{}，的用户没有可参加的问卷",token,starbucksAccount.getId());
                return AjaxResult.success("token为"+token+",id为"+starbucksAccount.getId()+"，的用户没有可参加的问卷");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("id:"+starbucksAccount.getId()+"获取调查问卷失败，token:"+token);
            return AjaxResult.error("id:"+starbucksAccount.getId()+"获取调查问卷失败，token:"+token);
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult getAnswer() {
        QueryStarbucksAccount queryStarbucksAccount = new QueryStarbucksAccount();
        queryStarbucksAccount.setIsValid("1");
        List<StarbucksAccount> starbucksAccountList = starbucksAccountExtMapper.selectStarbucksAccountList(queryStarbucksAccount);
        for (StarbucksAccount s:starbucksAccountList) {
            String token = s.getToken();
            String url = "https://bff.starbucks.com.cn/inbox/api/inbox?limit=10&offset=0&lang=zh&nonce=UD0eT%7EAz6CpU-XNa&sign=EQPCvub0%2Fq3WdtTqe%2BFZecdZioMIqWP%2FU%2FlYbikBY6XGQsclHs9WtI7za4V%2B3LGxlWCT9TAZsRwmRysLx909DFqE6jtafKm2irURYf%2FWrLLBSX3O0V%2F1aIKW442%2BcvbLturhSEAtr942z8ut%2BOViygdt%2BFqQRiaLMrl0mXRTS25VC%2F6OB9%2Fxy8Cwpf81uYgwwbV%2BYJuJ9UvHPIubU3FQC0UwxBlNw41XNXMlsyNEYVSB522eICrknuC81ilD2Rj%2F5jgt%2FMofjkAS5CneXCB8SyRd%2FuQEcTn5fDR7C5ynmp8uiv3HzNbxRhCP%2FkMd2bTQpUFk5eXDDALD9u4fXBIIbA%3D%3D";
            Map<String, Object> map = new HashMap<>();
            map.put("Connection", "keep-alive");
            map.put("Accept", "*/*");
            map.put("User-Agent", "Starbucks/7.19.0 (com.starbuckschina.mystarbucksmoments; build:3711; iOS 12.2.0) Alamofire/5.1.0");
            map.put("Accept-Language", "zh-Hans-CN;q=1.0");
            map.put("Accept-Encoding", "br;q=1.0, gzip;q=0.9, deflate;q=0.8");
            map.put("Authorization", "Bearer " + token);
            HttpResponseResult result = null;
            try {
                result = sendGet(url, null, map);
                if (!checkStarbucks(result)) {
                    return getAccountDetail(token);
                }
                String responseEntity = result.getResponseEntity();
                String title = "诚邀您参与啡快™顾客体验调查";
                if (responseEntity.contains(title)) {
                    log.info("有体验调查的："+s);
                }
            } catch (Exception exception) {

            }
        }
        return null;
    }

    //检查星巴克返回信息
    private static boolean checkStarbucks(HttpResponseResult result){
        if(result.getResponse()==null){
            updateProxy();
            return false;
        }
        int code = result.getResponse().getStatusLine().getStatusCode();
        //返回400，500,星巴克接口返回有误
        if (code==400||code==500){
            return false;
        }
        //如果返回错误网页，更新代理
        String responseEntity = result.getResponseEntity();
        if (responseEntity!=null&&responseEntity.contains("This page can't be displayed. Contact support for additional information")){
            updateProxy();
            return false;
        }
        return true;
    }

    //答题
    private static AnswerQuestionData submitAnswer(String url,String token,String params,Integer id){
        JSONObject data = new JSONObject();
        if (id>=3 && id <=17){
            data.put("test", 0);
            data.put( "lang", "cn");
            data.put("token", token);
            data.put("params", params);
        } else if (id == 0) {
            data.put("test", 0);
            data.put("lang", "cn");
            data.put("token", "");
            data.put("params", "");
        } else if (id == 4) {
            data.put("4", 5);
            data.put("test", 0);
            data.put("lang", "cn");
            data.put("token", token);
            data.put("params", params);
        } else if (id == 5){
            data.put("test", 0);
            data.put("lang", "cn");
            data.put("token", token);
            data.put("params", params);
            data.put("5_6", 7);
            data.put("5_7", 7);
            data.put("5_8", 7);
            data.put("5_9", 7);
            data.put("5_10", 7);
            data.put("5_11", 7);
            data.put("5_12", 7);
            data.put("5_13", 7);
            data.put("5_14", 7);
            data.put("5_15", 7);
            data.put("5_16", 7);
        }
        Map<String, Object> map = new HashMap<>();
//        map.put("Accept", "application/json, text/plain, */*");
//        map.put("Accept-Encoding", "gzip, deflate, br");
//        map.put("Accept-Language", "zh-CN,zh;q=0.9");
//        map.put("Connection", "keep-alive");
//        map.put("Origin", " https://mopsurvey.starbucks.com.cn");
        map.put("Content-Type", "application/json;charset=UTF-8");
        HttpResponseResult result = null;
        AnswerQuestionData questionData = new AnswerQuestionData();
        try {
            String jsonParams = String.valueOf(data);
            result = sendPost(url, jsonParams, map);
            JSONObject jsonObject = JSONObject.parseObject(result.getResponseEntity());
            if (jsonObject.getBoolean("success")) {
                String message = jsonObject.getString("message");
                if (message.equals("感谢您的参与")) {
                    questionData.setMessage(message);
                    return questionData;
                }
                questionData.setMessage(message);
                questionData.setToken(jsonObject.getJSONObject("data").getString("token"));
                questionData.setParams(jsonObject.getJSONObject("data").getString("next"));
                questionData.setId(jsonObject.getJSONObject("data").getJSONArray("questions").getJSONObject(0).getInteger("id"));
                return questionData;
            } else {
                questionData.setMessage(jsonObject.getString("message"));
                return questionData;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return questionData;
    }

    public void updateIp(){
        HttpResponse<JsonNode> response = Unirest.get(getProxyIpUrl).asJson();
        JSONObject ipData = JSONObject.parseObject(String.valueOf(response.getBody()));
        String proxy = ipData.getString("data");
        String[] str = proxy.split(":");
        proxyHost = str[0];
        proxyPort = Integer.parseInt(str[1]);
    }
}
